const Router = require("@koa/router");
const { gouwu, ObjectId } = require("../models/mongo");

const router = new Router({
    prefix: "/api",
});

// 获取post的body
const { bodyParser } = require("@koa/bodyparser");

// 添加购物车项的接口
router.post("/addGouwu", bodyParser(), async (ctx) => {
    const { cartItem, userid } = ctx.request.body;

    if (!cartItem || !userid) {
        ctx.status = 400;
        ctx.body = {
            code: 400,
            message: "Missing cartItem or userid",
        };
        return;
    }

    try {
        // 查找是否已有相同的商品
        const existingItem = await gouwu.findOne({ userid, "cartItem._id": cartItem._id });

        if (existingItem) {
            // 如果商品已存在，则更新数量
            const updatedCount = existingItem.cartItem.count + cartItem.count;
            const updateRes = await gouwu.updateOne(
                { userid, "cartItem._id": cartItem._id },
                { $set: { "cartItem.count": updatedCount, updatedAt: new Date() } }
            );

            if (updateRes.modifiedCount > 0) {
                ctx.body = {
                    code: 200,
                    message: "Quantity updated successfully",
                };
            } else {
                ctx.body = {
                    code: 500,
                    message: "Failed to update quantity",
                };
            }
        } else {
            // 如果商品不存在，直接插入
            const addPetRes = await gouwu.insertOne({
                _id: new ObjectId(cartItem._id),
                userid,
                cartItem,
                createdAt: new Date(),
            });

            if (addPetRes) {
                ctx.body = {
                    code: 200,
                    message: "Added to cart successfully",
                };
            } else {
                ctx.status = 500;
                ctx.body = {
                    code: 500,
                    message: "Failed to add item to cart",
                };
            }
        }
    } catch (error) {
        console.error("Error in addGouwu:", error);
        ctx.status = 500;
        ctx.body = {
            code: 500,
            message: "An error occurred while adding to the cart",
        };
    }
});




// 使用 POST 请求获取所有购物车数据

router.get("/getAllGouwu", async (ctx) => {
    const { page = 1, pageSize = 8 } = ctx.query;
    const total = await gouwu.countDocuments();

    const list = await gouwu
        .find()
        .skip((page - 1) * pageSize)
        .limit(pageSize * 1)
        .sort({ _id: -1 })
        .toArray();
    ctx.body = {
        code: 200,
        message: "success",
        total,
        page,
        pageSize,
        list,
    }
});



router.post("/delGouwu", bodyParser(), async (ctx) => {
    const { id } = ctx.request.body;
    const delPetRes = await gouwu.deleteOne({ _id: new ObjectId(id) })

    if (delPetRes) {
        ctx.body = {
            code: 200,
            message: "success",
        };
    }
});






module.exports = router;
